﻿/*
  DISCLAIMER:
THIS CODE IS SAMPLE CODE. THESE SAMPLES ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
MICROSOFT FURTHER DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR OF FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF THE USE OR PERFORMANCE OF THE SAMPLES REMAINS WITH YOU. IN NO EVENT SHALL
MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE
SAMPLES, EVEN IF MICROSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION
OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.
 * */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Reflection;
using System.Net.Sockets;

namespace WebDAV_Test_Application
{

    public partial class FormListener : Form
    {
        private UdpClient _UDPListener = null;
        private string _ListenURi = "";
        private int _ListenPort = 36728;
        private List<string> _Requests;
        private ClassLogger _Logger = null;

        public FormListener()
        {
            InitializeComponent();

            _Requests = new List<string>();

            hScrollBarReceived.Value = 0;
            hScrollBarReceived.Maximum = 0;
            hScrollBarReceived.Minimum = 0;

            _Logger = new ClassLogger(Path.GetDirectoryName(Application.ExecutablePath) + "\\Listener Log.txt");

            StartListening();
        }

        public FormListener(ClassLogger Logger)
        {
            InitializeComponent();

            _Requests = new List<string>();

            hScrollBarReceived.Value = 0;
            hScrollBarReceived.Maximum = 0;
            hScrollBarReceived.Minimum = 0;

            _Logger = Logger;

            StartListening();
        }

        ~FormListener()
        {
            _Logger = null;
            GC.Collect();
        }

        
        private void StartListening()
        {
            textBoxListenerURi.Text = "httpu://" + Environment.MachineName + ":" + _ListenPort + "/";
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, _ListenPort);
            _UDPListener = new UdpClient(ip);
            _UDPListener.BeginReceive(new AsyncCallback(UDPListenerCallback), _UDPListener);
        }

        public int Port
        {
            get
            {
                return _ListenPort;
            }
            set
            {
                if (value == _ListenPort) return;
                _UDPListener.Close();
                _ListenPort = value;
                StartListening();
            }
        }

        public string URi
        {
            get
            {
                return _ListenURi;
            }
        }

        public void UDPListenerCallback(IAsyncResult result)
        {
            UdpClient listener = (UdpClient)result.AsyncState;
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, _ListenPort);

            Byte[] receiveBytes=listener.EndReceive(result,ref ip);
            string sReceived = Encoding.ASCII.GetString(receiveBytes);
            AddRequest(sReceived);
            _UDPListener.BeginReceive(new AsyncCallback(UDPListenerCallback), _UDPListener);
        }

        private void AddRequest(string Request)
        {
            _Requests.Add(Request);
            Log(Request, "Notification");
            int iRequestCount = _Requests.Count;

            if (hScrollBarReceived.InvokeRequired)
            {
                hScrollBarReceived.Invoke((MethodInvoker)delegate
                {
                    hScrollBarReceived.Maximum = iRequestCount;
                    if (hScrollBarReceived.Minimum == 0)
                        hScrollBarReceived.Minimum = 1;
                    if (hScrollBarReceived.Value == (iRequestCount - 1))
                        hScrollBarReceived.Value = iRequestCount;
                    hScrollBarReceived.Refresh();
                });
            }
            else
            {
                hScrollBarReceived.Maximum = iRequestCount;
                if (hScrollBarReceived.Minimum == 0)
                    hScrollBarReceived.Minimum = 1;
                if (hScrollBarReceived.Value == (iRequestCount - 1))
                    hScrollBarReceived.Value = iRequestCount;
                hScrollBarReceived.Refresh();
            }
            ShowCurrentRequest();
        }

        private void ShowCurrentRequest()
        {
            // Update info textbox (nav)
            string sShowing = hScrollBarReceived.Value + " of " + _Requests.Count;
            if (textBoxReceivedShowing.InvokeRequired)
            {
                textBoxReceivedShowing.Invoke((MethodInvoker)delegate
                {
                    textBoxReceivedShowing.Text = sShowing;
                });
            }
            else
                textBoxReceivedShowing.Text = sShowing;

            // Update request textbox
            string sRequest = _Requests[hScrollBarReceived.Value-1];
            if (textBoxReceived.InvokeRequired)
            {
                textBoxReceived.Invoke((MethodInvoker)delegate
                {
                    textBoxReceived.Text = sRequest;
                });
            }
            else
                textBoxReceived.Text = sRequest;
        }

        private void hScrollBarReceived_ValueChanged(object sender, EventArgs e)
        {
            ShowCurrentRequest();
        }

        private void Log(string Details, string Description = "")
        {
            try
            {
                if (_Logger == null) return;
                _Logger.Log(Details, Description);
            }
            catch { }
        }

    }
}
